package com.x.wx.dao;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.x.framework.dao.BaseDao;
import com.x.wx.model.WxAccount;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/3/6.
 */

@Repository
public class WxAccountDao extends BaseDao{

	private final static  String  selectWxAccountListSql = "SELECT T1.* FROM WX_ACCOUNT T1 WHERE 1=1 ";

	/**
	 * 查询微信公众号列表
	 * @param wxAccount
	 * @return
	 * @throws Exception
	 */

	public List<WxAccount> selectWxAccountList(WxAccount wxAccount) throws Exception{
		StringBuilder sql = new StringBuilder(selectWxAccountListSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, wxAccount);
		sql.append("ORDER BY T1.CREATE_TIME ASC");
		return this.queryForList(sql.toString(), WxAccount.class, params, wxAccount);
	}

	private final static  String  selectWxAccountNumSql = "SELECT COUNT(T1.WX_ACCOUNT_ID) FROM WX_ACCOUNT T1 WHERE 1=1 ";

	/**
	 * 查询微信公众号数量
	 * @param wxAccount
	 * @return
	 * @throws Exception
	 */

	public int selectWxAccountNum(WxAccount wxAccount) throws Exception{
		StringBuilder sql = new StringBuilder(selectWxAccountNumSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, wxAccount);
		return this.queryForInt(sql.toString(), params);
	}

	public WxAccount selectWxAccountById(WxAccount wxAccount) throws Exception {
        StringBuilder sb = new StringBuilder(selectWxAccountListSql);
        List<Object> params = new ArrayList<Object>();
        if(this.isNotNull(wxAccount.getWxAccountId())){
            sb.append("AND T1.WX_ACCOUNT_ID = ? ");
            params.add(wxAccount.getWxAccountId());
            return this.queryForList(sb.toString(),  WxAccount.class, params).get(0);
        }
        return new WxAccount();
    }

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param wxAccount
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, WxAccount wxAccount) {
		if(wxAccount != null) {
			if(StringUtils.isNotEmpty(wxAccount.getMarketId())){
				sql.append("AND T1.MARKET_ID = ? ");
				params.add(wxAccount.getMarketId());
			}
			if(wxAccount.getWxAccountState() != null ){
				sql.append("AND T1.WX_ACCOUNT_STATE = ? ");
				params.add(wxAccount.getWxAccountState());
			}
			if(wxAccount.getWxEncryptMessage() != null ){
				sql.append("AND T1.WX_ENCRYPT_MESSAGE = ? ");
				params.add(wxAccount.getWxEncryptMessage());
			}
		}
	}


}
